<template>
  <div class="weather-container">
    <!-- 导航栏 -->
    <van-nav-bar
        title="天气"
        left-arrow
        @click-left="onClickLeft"
        fixed
    />

    <!-- 错误提示 -->
    <div v-if="error" class="error-container">
      <van-empty
          image="error"
          :description="error"
      >
        <template #bottom>
          <van-button round type="primary" @click="retryLoad">
            重新加载
          </van-button>
        </template>
      </van-empty>
    </div>

    <div class="content" v-else-if="!loading">
      <!-- 顶部天气卡片 -->
      <div class="weather-card">
        <div class="current-weather">
          <div class="temperature">{{ weather.temp }}°</div>
          <div class="weather-info">
            <div class="weather-text">{{ weather.text }}</div>
            <div class="location">
              <van-icon name="location-o" />
              {{ scenicSpot.name }}
            </div>
          </div>
        </div>
        <div class="weather-details">
          <div class="detail-item">
            <van-icon name="water-o" />
            <span>湿度</span>
            <span>{{ weather.humidity }}%</span>
          </div>
          <div class="detail-item">
            <van-icon name="guide-o" />
            <span>风向</span>
            <span>{{ weather.windDir }}</span>
          </div>
          <div class="detail-item">
            <van-icon name="flag-o" />
            <span>风速</span>
            <span>{{ weather.windSpeed }}km/h</span>
          </div>
        </div>
      </div>

      <!-- 24小时预报部分 -->
      <div class="hourly-forecast">
        <div v-for="(item, index) in hourlyForecast"
             :key="index"
             class="forecast-item">
          <span class="time">{{ item.time }}</span>
          <i :class="['qi-' + item.icon]" class="weather-icon"></i>
          <span class="temp">{{ item.temp }}°</span>
        </div>
      </div>

      <!-- 7天预报部分 -->
      <div class="daily-forecast">
        <div v-for="(item, index) in dailyForecast"
             :key="index"
             class="daily-item">
          <span class="date">{{ item.date }}</span>
          <i :class="['qi-' + item.iconDay]" class="weather-icon"></i>
          <div class="temp-range">
            <span class="max">{{ item.tempMax }}°</span>
            <span class="divider">/</span>
            <span class="min">{{ item.tempMin }}°</span>
          </div>
        </div>
      </div>

      <!-- 更新时间 -->
      <div class="update-time" v-if="updateTime">
        更新时间：{{ updateTime }}
      </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading-container" v-else>
      <van-loading type="spinner" color="#1989fa" size="24px">
        加载中...
      </van-loading>
    </div>
  </div>
</template>

<script>

import axios from 'axios';
import { Toast } from 'vant';

export default {
  name: 'Weather',
  data() {
    return {
      loading: true,
      error: null,
      scenicSpot: {
        name: '获取中...',
        location: {
          longitude: null,
          latitude: null
        }
      },
      weather: {
        temp: '--',
        text: '未知',
        humidity: '--',
        windDir: '--',
        windSpeed: '--',
        icon: '100'
      },
      hourlyForecast: [],
      dailyForecast: [],
      updateTime: '--'
    }
  },

  created() {
    this.initLocation();
    this.initWeather();
  },

  methods: {
    onClickLeft() {
      this.$router.back();
    },

    retryLoad() {
      this.initWeather();
    },

    async initLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(async (position) => {
          this.scenicSpot.location.longitude = position.coords.longitude;
          this.scenicSpot.location.latitude = position.coords.latitude;

          // 获取详细地址
          const address = await this.getAddressFromCoordinates(
              this.scenicSpot.location.latitude,
              this.scenicSpot.location.longitude
          );
          this.scenicSpot.name = address || '未知位置'; // 更新为详细地址
          this.initWeather(); // 获取天气数据
        }, (error) => {
          console.error('获取位置失败:', error);
          this.error = '无法获取位置';
          this.loading = false;
        });
      } else {
        console.error('浏览器不支持地理位置服务');
        this.error = '浏览器不支持地理位置服务';
        this.loading = false;
      }
    },

    async getAddressFromCoordinates(lat, lon) {
      try {
        const response = await axios.get(`https://api.map.baidu.com/geocoding/v3/?ak=YOUR_BAIDU_MAP_AK&output=json&location=${lat},${lon}`);
        if (response.data && response.data.status === 0) {
          return response.data.result.formatted_address; // 返回详细地址
        }
      } catch (error) {
        console.error('获取地址失败:', error);
      }
      return null;
    },

    async initWeather() {
      this.loading = true;
      this.error = null;

      try {
        const { nowRes, hourlyRes, dailyRes } = await this.getWeatherData(
            this.scenicSpot.location.latitude,
            this.scenicSpot.location.longitude
        );

        // 检查响应状态和数据
        if (!nowRes.data || !hourlyRes.data || !dailyRes.data) {
          throw new Error('获取天气数据失败');
        }

        // 更新天气数据
        this.updateCurrentWeather(nowRes.data.data.now);
        this.updateHourlyForecast(hourlyRes.data.data.hourly);
        this.updateDailyForecast(dailyRes.data.data.daily);

        // 更新时间
        this.updateTime = this.formatDateTime(nowRes.data.data.updateTime);
      } catch (error) {
        this.error = '获取天气数据失败';
        console.error('Weather init error:', error);
      } finally {
        this.loading = false;
      }
    },

    async getWeatherData(lat, lon) {
      try {
        // 调用实时天气
        const nowRes = await axios.get('http://localhost:9999/api-central-service/api/weather/now', {
          params: { lat, lon }
        });

        // 调用24小时预报
        const hourlyRes = await axios.get('http://localhost:9999/api-central-service/api/weather/forecast/24h', {
          params: { lat, lon }
        });

        // 调用7天预报
        const dailyRes = await axios.get('http://localhost:9999/api-central-service/api/weather/forecast/7d', {
          params: { lat, lon }
        });

        return { nowRes, hourlyRes, dailyRes };
      } catch (error) {
        console.error('Weather API Error:', error);
        throw error;
      }
    },

    updateCurrentWeather(data) {
      if (!data) return;
      this.weather = {
        temp: data.temp || '--',
        text: data.text || '未知',
        humidity: data.humidity || '--',
        windDir: data.windDir || '--',
        windSpeed: data.windSpeed || '--',
        icon: data.icon || '100'
      };
    },

    updateHourlyForecast(data) {
      if (!data) return;
      this.hourlyForecast = data.map(item => ({
        time: this.formatTime(item.fxTime),
        temp: item.temp,
        icon: item.icon
      })).slice(0, 24);
    },

    updateDailyForecast(data) {
      if (!data) return;
      this.dailyForecast = data.map(item => ({
        date: this.formatDate(item.fxDate),
        tempMin: item.tempMin,
        tempMax: item.tempMax,
        iconDay: item.iconDay,
        textDay: item.textDay
      }));
    },

    formatTime(timeStr) {
      if (!timeStr) return '--:--';
      const date = new Date(timeStr);
      return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },

    formatDate(dateStr) {
      if (!dateStr) return '--/--';
      const date = new Date(dateStr);
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return `${weekdays[date.getDay()]} ${date.getMonth() + 1}/${date.getDate()}`;
    },

    formatDateTime(timeStr) {
      if (!timeStr) return '--/-- --:--';
      const date = new Date(timeStr);
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },

    getWeatherIconUrl(icon) {
      if (!icon) return '';
      return `https://qweather.com/icons/202106d/${icon}.png`;
    }
  }
}
</script>

<style scoped>
.weather-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}

.content {
  padding: 16px;
}

.weather-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.current-weather {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.temperature {
  font-size: 48px;
  font-weight: bold;
  margin-right: 16px;
  color: #1989fa;
}

.weather-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.weather-text {
  font-size: 18px;
  color: #323233;
}

.location {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #969799;
  font-size: 14px;
}

.weather-details {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  color: #323233;
}

.forecast-section {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #323233;
  font-size: 16px;
  font-weight: bold;
}

.hourly-forecast {
  display: flex;
  overflow-x: auto;
  padding: 8px 0;
  gap: 20px;
}

.forecast-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  min-width: 60px;
}

.weather-icon {
  width: 24px;
  height: 24px;
}

.daily-forecast {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.daily-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.daily-item .date {
  width: 100px;
  color: #323233;
}

.temp-range {
  width: 80px;
  text-align: right;
}

.temp-range .max {
  color: #ee0a24;
}

.temp-range .min {
  color: #1989fa;
}

.temp-range .divider {
  margin: 0 4px;
  color: #969799;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 46px);
}

.update-time {
  text-align: center;
  color: #969799;
  font-size: 12px;
  padding: 8px 0;
}

::-webkit-scrollbar {
  display: none;
}

/* 适配刘海屏 */
.van-nav-bar {
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
}

.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 46px);
  padding: 20px;
}

/* 修改图标样式 */
.weather-icon {
  font-size: 24px;
  color: #323233;
}

/* 可以添加图标动画效果 */
.weather-icon {
  transition: transform 0.3s ease;
}
.weather-icon:hover {
  transform: scale(1.1);
}
</style>